import { Adventure } from '@/business/adventure/entities/adventure.entity';
import { Attachement } from '@/business/attachement/entities/attachement.entity';
import { Role } from '@/business/role/entities/role.entity';
import { Task } from '@/business/task/entities/task.entity';
import { CommonEntity } from '@/common/common-entity';
import { ApiPropertyOptional } from '@nestjs/swagger';
import {
  Column,
  Entity,
  JoinColumn,
  JoinTable,
  ManyToMany,
  ManyToOne,
  OneToMany,
  OneToOne
} from 'typeorm';
@Entity('user')
export class User extends CommonEntity {
  @ApiPropertyOptional({ description: '用户账号', example: 'admin' })
  @Column({
    type: 'varchar',
    unique: true,
    comment: '用户账号',
    length: 255
  })
  username: string;

  @ApiPropertyOptional({ description: '密码', example: '123456' })
  @Column({ type: 'varchar', comment: '密码', length: 255, select: false })
  password: string;

  @ApiPropertyOptional({ description: '是否为管理员', example: 0 })
  @Column({ type: 'tinyint', comment: '是否为管理员', width: 1, default: 0 })
  isAdmin: number;

  @ApiPropertyOptional({ description: '真实姓名', example: '抹茶' })
  @Column({ type: 'varchar', nullable: true, comment: '真实姓名', length: 16 })
  realname: string;

  @ApiPropertyOptional({ description: '电话号码', example: '1388888888' })
  @Column({ type: 'varchar', nullable: true, comment: '电话号码', length: 16 })
  phone: string;

  @ApiPropertyOptional({ description: '邮箱', example: 'matcha@163.com' })
  @Column({ type: 'varchar', nullable: true, comment: '邮箱', length: 32 })
  email: string;

  // 用户 多对多 角色
  @ApiPropertyOptional({ description: '角色', type: [Role] })
  // 第一个参数：表示和哪个实体建立关系，第二个参数：定义Role实体中反向关系的属性名，说明在Role实体中存在一个返回的users字段属性，存储与此Role关联的实例列表
  @ManyToMany(() => Role, (role) => role.users, {
    createForeignKeyConstraints: false, // 是否创建外键约束，false 否
    cascade: true // 当对当前实体实例进行操作（如保存、更新、删除）时，是否应该级联这些操作到关联的Role实体实例 true 是
  })
  @JoinTable({ name: 'user_role' }) // 重命名关联表的表名
  roles: Role[];

  // @ApiPropertyOptional({ description: '头像', type: Attachement })
  @OneToOne(() => Attachement, (attachement) => attachement.user, {
    cascade: true,
    createForeignKeyConstraints: false
  })
  @JoinColumn()
  avatar: Attachement;

  // 一个用户可以发布多个任务 一对多
  @OneToMany(() => Task, (task) => task.publisher, {
    eager: false // 是否在查询User时立即加载关联的Task
  })
  tasks: Task[];

  // 一个用户只能加入一个冒险者小队
  @ManyToOne(() => Adventure, (adventure) => adventure.members, {
    onDelete: 'SET NULL'
  })
  adventure: Adventure;
  members: User[];
}
